import exifread
from geoModule import loacation2address
from keys import gaode_key
class exifClass():
    def __init__(self,gaode_key=''):
        self.gaode_key=gaode_key##高德地图api keys
    def run(self,path):

        exif_dict={}
        result={}
        try:
            with open(path, 'rb') as f:
                exif_dict = exifread.process_file(f)
        except Exception as e:
            print(e)
            pass
            print('no exif')
        if exif_dict!={}:

            location=[]
            picTime=[]
            try:
                picTime= str(exif_dict['EXIF DateTimeOriginal']).split(' ')
                # 经度
                lon_ref = exif_dict["GPS GPSLongitudeRef"].printable
                lon = exif_dict["GPS GPSLongitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
                lon = float(lon[0]) + float(lon[1]) / 60 + float(lon[2]) / float(lon[3]) / 3600
                if lon_ref != "E":
                    lon = lon * (-1)

                # 纬度
                lat_ref = exif_dict["GPS GPSLatitudeRef"].printable
                lat = exif_dict["GPS GPSLatitude"].printable[1:-1].replace(" ", "").replace("/", ",").split(",")
                lat = float(lat[0]) + float(lat[1]) / 60 + float(lat[2]) / float(lat[3]) / 3600
                if lat_ref != "N":
                    lat = lat * (-1)
                location=str(lon)+","+str(lat)

                if len(location)>0:
                    print('照片的经纬度：', location)
                    addressDict=loacation2address(location, self.gaode_key)
            except Exception as e:
                print(e)
            ######
            if len(location)>0:
                result = dict(result, **{'location':location})
            if len(addressDict)>0:
                result = dict(result, **addressDict)
            if len(picTime)>0:
                result = dict(result, **{'date':picTime[0]})
                result = dict(result, **{'time':picTime[1]})


            return result

        return {}
##返回示例：{'location': '113.271917,23.096571972222222', 'city': '广州市',
# 'province': '广东省', 'district': '海珠区', 'township': '江南中街道', 'date': '2021:08:07', 'time': '21:42:11'}


if __name__=='__main__':
    ec=exifClass(gaode_key)
    path='testpic/test1.jpg'
    print( ec.run(path))
